package com.wkbb.basic.controller.manage;

import com.github.pagehelper.PageInfo;
import com.wkbb.basic.enums.FaceReportTargetEnum;
import com.wkbb.basic.model.UserFaceOrder;
import com.wkbb.basic.service.StudentService;
import com.wkbb.basic.service.UserFaceReportService;
import com.wkbb.basic.vo.FaceReportVo;
import com.wkbb.basic.vo.UserFaceOrderVo;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lizhichao
 * @date 2019/11/11
 * @description
 */
@Slf4j
@RestController
@Api(description = "用户人脸报表")
@RequestMapping("/basic/{apiVersion}/faceReport/order")
public class UserFaceReportController extends BaseController {

    @Autowired
    private UserFaceReportService userFaceReportService;

    @Autowired
    private StudentService studentService;

    @ApiOperation("查询总部人脸报表分页列表")
    @RequestMapping(value = "/getHeadQuartFaceReportPageInfoList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<FaceReportVo>> getHeadQuartFaceReportPageInfoList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织类型（1超管 2代理商）", required = true) @RequestParam(name = "orgType", required = true) int orgType,
            @ApiParam(value = "组织ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "页码", required = false, defaultValue = "1") @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false, defaultValue = "10") @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        log.info("***********UserFaceReportController.getHeadQuartFaceReportPageInfoList******...orgId:{}", orgId);
        try {
            //查看代理商报表列表
            if (orgType == 1) {
                return new ResultDTO(userFaceReportService.getHeadQuartFaceReportPageInfoList(new HashMap<>(), pageNo, pageSize));
            }
            //查看学校报表列表
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("orgId", orgId);

            return new ResultDTO(userFaceReportService.getAgentFaceReportPageInfoList(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("***********UserFaceReportController.getHeadQuartFaceReportPageInfoList******查询总部人脸报表分页列表", e);
            return new ResultDTO<>(false);
        }

    }

    @ApiOperation("查询代理商人脸报表分页列表")
    @RequestMapping(value = "/getAgentFaceReportPageInfoList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<FaceReportVo>> getAgentFaceReportPageInfoList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "学校名称", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "日期（格式YYYY-MM-DD）", required = false) @RequestParam(name = "dateTime", required = false) String dateTime,
            @ApiParam(value = "页码", required = false, defaultValue = "1") @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false, defaultValue = "10") @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        log.info("***********UserFaceReportController.getAgentFaceReportPageInfoList******...orgId:{},name:{},dateTime:{}", orgId, name, dateTime);
        try {

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("orgId", orgId);
            if (!StringUtil.isEmpty(name)) {
                params.put("targetName", name);
            }
            if (!StringUtil.isEmpty(dateTime)) {
                params.put("dateTime", dateTime);
            }

            return new ResultDTO(userFaceReportService.getAgentFaceReportPageInfoList(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("***********UserFaceReportController.getAgentFaceReportPageInfoList******查询代理商人脸报表分页列表", e);
            return new ResultDTO<>(false);
        }

    }

    @ApiOperation("查询订单记录和发放记录")
    @RequestMapping(value = "/getFaceOrderRecordList", method = RequestMethod.GET)
    public ResultDTO<UserFaceOrderVo> getFaceOrderRecordList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "类型（1发放记录 2订单记录）", required = true) @RequestParam(name = "type", required = true) Byte type,
            @ApiParam(value = "目标组织ID（当类型为1的时候必传）", required = false) @RequestParam(name = "targetId", required = false) Long targetId) {

        log.info("***********UserFaceReportController.getFaceOrderRecordList******...orgId:{},type:{},targetId:{}", orgId, type, targetId);
        try {

            Map<String, Object> params = new HashMap<String, Object>();
            //查询发放记录
            if (type == 1) {
                if(targetId == null){
                    return new ResultDTO<>(ErrorCode.PARAM_MISSING);
                }
                params.put("orgId", orgId);
                params.put("targetId", targetId);
            } else {
                params.put("targetId", orgId);
            }

            return new ResultDTO(userFaceReportService.getFaceOrderHistory(params));
        } catch (Exception e) {
            log.error("***********UserFaceReportController.getFaceOrderRecordList******查询订单记录和发放记录异常", e);
            return new ResultDTO<>(false);
        }

    }

    @ApiOperation("获取库存详情")
    @RequestMapping(value = "/getFaceStoreInfo", method = RequestMethod.GET)
    public ResultDTO<FaceReportVo> getFaceStoreInfo(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "对象id(objectType=1是orgId，objectType=2为学生id)", required = true) @RequestParam(name = "objectId", required = true) Long objectId,
            @ApiParam(value = "对象类型（1代理商,学校 2学生）", required = true) @RequestParam(name = "objectType", required = true) Long objectType) {

        log.info("***********UserFaceReportController.getFaceStoreInfo******...objectId:{},objectType:{}", objectId, objectType);
        try {

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("objectId", objectId);
            params.put("objectType", objectType);

            return new ResultDTO(userFaceReportService.getUserFaceStoreInfo(params));
        } catch (Exception e) {
            log.error("***********UserFaceReportController.getFaceStoreInfo******获取库存详情异常", e);
            return new ResultDTO<>(false);
        }

    }

    @ApiOperation("下放人脸（超管，代理商）")
    @RequestMapping(value = "/addUserFaceOrder", method = RequestMethod.POST)
    public ResultDTO<Object> addUserFaceOrder(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "发放者组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "发放目标对象组织ID", required = true) @RequestParam(name = "targetId", required = true) Long targetId,
            @ApiParam(value = "发放数量", required = true) @RequestParam(name = "amount", required = true) int amount,
            @ApiParam(value = "赠送数量", required = false) @RequestParam(name = "giveAmount", required = false) int giveAmount,
            @ApiParam(value = "备注", required = false) @RequestParam(name = "remark", required = false) String remark) {
        log.info("***********UserFaceReportController.addUserFaceOrder******...orgId:{},targetId:{},amount:{},giveAmount:{},remark:{}", orgId, targetId, amount, giveAmount, remark);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            UserFaceOrder userFaceOrder = new UserFaceOrder();
            userFaceOrder.setOrgId(orgId);
            userFaceOrder.setTargetId(targetId);
            userFaceOrder.setAmount(amount);
            userFaceOrder.setGiveAmount(giveAmount);
            userFaceOrder.setRemark(remark);
            userFaceOrder.setOrderType((byte)1);//下放
            userFaceOrder.setTargetType(FaceReportTargetEnum.ORGANIZATION.getValue());//超管 代理商

            //超管身份
            Boolean isSuper = false;
            if (this.getUserIsSuper(userDto)) {
                userFaceOrder.setUserName("微看客服");
                isSuper = true;
            } else {
                userFaceOrder.setUserName(userDto.getName());
            }

            userFaceReportService.insert(userFaceOrder, isSuper);
            return new ResultDTO(true);
        } catch (Exception e) {
            log.error("***********BlacklistController.addUserFaceOrder******下放人脸异常", e);
            return new ResultDTO<>(false);
        }

    }

    @ApiOperation("开通，回收人脸（学校）")
    @RequestMapping(value = "/addUserFaceOrderForStudent", method = RequestMethod.POST)
    public ResultDTO<Object> addUserFaceOrderForStudent(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "学生用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId,
            @ApiParam(value = "订单类型（1开通 2回收）", required = true) @RequestParam(name = "orderType", required = true) Byte orderType) {
        log.info("***********UserFaceReportController.addUserFaceOrderForStudent******...orgId:{},userId:{},orderType:{}", orgId, userId, orderType);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            UserFaceOrder userFaceOrder = new UserFaceOrder();
            userFaceOrder.setOrgId(orgId);
            userFaceOrder.setAmount(1);
            userFaceOrder.setTargetId(userId);
            userFaceOrder.setTargetType(FaceReportTargetEnum.STUDENT.getValue());//学生
            userFaceOrder.setOrderType(orderType);
            userFaceOrder.setUserId(userDto.getId());
            userFaceOrder.setUserName(userDto.getName());

            userFaceReportService.addUserFaceOrderForStudent(userFaceOrder);
            return new ResultDTO(true);
        } catch (Exception e) {
            log.error("***********BlacklistController.addUserFaceOrderForStudent******开通，回收人脸（学校）", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation("批量开通人脸（学校）")
    @RequestMapping(value = "/addUserFaceOrderBatch", method = RequestMethod.POST)
    public ResultDTO<Object> addUserFaceOrderBatch(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "班级ID", required = true) @RequestParam(name = "classId", required = true) Long classId,
            @ApiParam(value = "批量开通数量", required = true) @RequestParam(name = "amount", required = true) int amount) {
        log.info("***********UserFaceReportController.addUserFaceOrderBatch******...orgId:{},userId:{},amount:{}", orgId, classId, amount);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }
        if (orgId == 0 || classId == 0) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            Map<String, Object> params = new HashMap<>(2);
            params.put("orgId", orgId);
            params.put("classId", classId);
            List<StudentInfoDto> studentInfoDtos = studentService.getStudentInfoList(params);

            //1,先校验学校库存是否足够
            FaceReportVo faceReportVo = userFaceReportService.getUserFaceStoreInfo(params);
            if(faceReportVo.getReserveCount() < amount * studentInfoDtos.size()){

                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            //2,批量开通人脸
            List<UserFaceOrder> userFaceOrders = new ArrayList<>();
            if (!CollectionUtils.isNotEmpty(studentInfoDtos)) {
                for (StudentInfoDto studentInfoDto : studentInfoDtos) {
                    UserFaceOrder userFaceOrder = new UserFaceOrder();
                    userFaceOrder.setOrgId(orgId);
                    userFaceOrder.setAmount(amount);
                    userFaceOrder.setTargetId(studentInfoDto.getUserId());
                    userFaceOrder.setTargetType(FaceReportTargetEnum.STUDENT.getValue());//学生
                    userFaceOrder.setOrderType((byte) 1);//下放
                    userFaceOrder.setUserId(userDto.getId());
                    userFaceOrder.setUserName(userDto.getName());
                    userFaceOrders.add(userFaceOrder);
                }
            }

            userFaceReportService.addUserFaceOrderBatch(userFaceOrders);
            return new ResultDTO(true);
        } catch (Exception e) {
            log.error("***********BlacklistController.addUserFaceOrderBatch******批量开通人脸（学校）异常", e);
            return new ResultDTO<>(false);
        }
    }

}
